package com.jn.algorithm.other.question721;

import java.io.StringReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 江南大学1033190417
 * @date 2022/5/21 20:25
 */
public class Solution {
    public List<List<String>> accountsMerge(List<List<String>> accounts) {
        List<List<String>> res = new ArrayList<>();
        List<Integer> hasDeal=new ArrayList<>();
        int size = accounts.size();
        while (hasDeal.size()!=size) {
            for (int i = 0; i < size; i++) {
                if (hasDeal.contains(i)){
                    continue;
                }
                hasDeal.add(i);
                List<String> cur=accounts.get(i);
                for (int j = 0; j < size; j++) {
                    if (hasDeal.contains(j)){
                        continue;
                    }
                    List<String> now = accounts.get(j);
                    if (isHeBing(cur,now)){
                        hasDeal.add(j);
                        cur=heBing(cur,now);
                    }
                }
                res.add(cur);
            }
        }
        return res;
    }

    public boolean isHeBing(List<String> a1, List<String> a2) {
        int l1 = a1.size();
        for (int i = 1; i < l1; i++) {
            if (a2.contains(a1.get(i))) {
                return true;
            }
        }
        return false;
    }

    public List<String> heBing(List<String> a1, List<String> a2) {
        String name = a1.get(0);
        //去掉名字
        a1.remove(0);
        a2.remove(0);

        a1.addAll(a2);
        HashSet<String> set = new HashSet<>(a1);
        Deque<String> r = new LinkedList<>(set);
        a1=new ArrayList<>(r);
        a1.sort(String::compareTo);
        r=new LinkedList<>(a1);
        r.addFirst(name);
        return new ArrayList<>(r);
    }


    public static void main(String[] args) {
        List<String> a1 = new ArrayList<>();
        a1.add("ms");
        a1.add("123.com");
        a1.add("1235456.com");

        List<String> a2 = new ArrayList<>();
        a2.add("ms");
        a2.add("123.com");
        a2.add("1235@qq.com");

        Solution solution = new Solution();
        System.out.println(solution.heBing(a1, a2));
    }
}
